package com.lmc.forum.controller;


import com.lmc.forum.common.AppResult;
import com.lmc.forum.common.ResultCode;
import com.lmc.forum.config.AppConfig;
import com.lmc.forum.model.Article;
import com.lmc.forum.model.User;
import com.lmc.forum.services.impl.ArticleServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Tag(name = "文章管理")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleServiceImpl articleService;

    @Operation(summary = "添加文章")
    @PostMapping("/create")
    public AppResult insert(HttpServletRequest request,
                            @Parameter(description = "板块ID", required = true, example = "1")
            @RequestParam(value = "boardId") @NotNull Long boardId,
                            @Parameter(description = "标题", required = true, example = "标题")
            @RequestParam(value = "title") @NotBlank String title,
                            @Parameter(description = "内容", required = true, example = "内容")
            @RequestParam(value = "content") @NotBlank String content
    ) {

        Article article = new Article();

//        获取用户id
        User user = (User) request.getSession().getAttribute(AppConfig.USER_SESSION);

        // 判断是否被禁⾔
        if (user.getState() == 1) {
// 返回错误信息
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        articleService.insertSelective(article);
        return AppResult.success(ResultCode.SUCCESS);
    }

    @Operation(summary = "获取文章")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(
            @Parameter(description = "板块ID", required = false, example = "1")
            @RequestParam(value = "boardId", required = false)
            Long boardId
    ) {
        List<Article> articles = null;
        if (boardId == null) {
             articles = articleService.selectAll();
             log.info("获取所有文章");
        }else{
            articles = articleService.selectByBoardId(boardId);
            log.info("根据板块id获取文章");
        }

        if (articles == null) {
//            为了规范性，返回空列表
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    @Operation(summary = "获取文章详情")
    @GetMapping("/getById")
    public AppResult<Article> getDetailById(
            HttpServletRequest request,
            @Parameter(description = "文章ID", required = true, example = "1")
            @RequestParam(value = "id") @NotNull Long id
    ){
        log.info("获取文章详情");
        Article article = articleService.selectDetailByArticleId(id);
        if(article == null){
            log.warn(ResultCode.FAILED_ARTICAL_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_ARTICAL_NOT_EXISTS);
        }
        User user = (User) request.getSession().getAttribute(AppConfig.USER_SESSION);
        if(article.getUserId() == user.getId()){
            article.setOwn( true );
        }
        return AppResult.success(article);
    }

    @Operation(summary = "修改文章")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @Parameter(description = "帖⼦Id") @RequestParam(value = "id")
                            @NotNull Long id,
                            @Parameter(description = "⽂章标题") @RequestParam(value =
                                    "title") @NotNull String title,
                            @Parameter(description = "帖⼦内容") @RequestParam(value =
                                    "content") @NotNull String content) {
// 获取⽤⼾信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
// 判断是否被禁⾔
        if (user.getState() != 0) {
// ⽇志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
// 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
// 获取帖⼦原始数据
            Article article = articleService.selectById(id);
// 数据校验
        if (article == null) {
            log.warn("修改的帖⼦不存在. articleId = " + id);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
// 发帖⼈不是当前⽤⼾
        if (article.getUserId() != user.getId()) {
            log.warn(MessageFormat.format("发帖⼈不是当前⽤⼾. article id = {0}, article user id = {1}, " +
                    "current user id = {2}", article.getId(), article.getUserId(), user.getId()));
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
// 帖⼦状态异常
        if (article.getState() != 0 ) {
            log.warn("帖⼦状态异常. articleId = " + id + ", state = " +
                    article.getState() );
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
// 调⽤业务层
        articleService.modify(id, title, content);
// ⽇志
        log.info(MessageFormat.format("帖⼦修改成功. id = {0}, user id = {1}, 原标题 = {2}, 新标题 = {3}",
                id, user.getId(), article.getTitle(), title));
// 返回结果
        return AppResult.success();
    }

    @Operation(summary = "点赞")
    @RequestMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                         @Parameter(description = "帖⼦ID") @RequestParam(value = "id")
                          @NotNull Long id
                         ){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " +
                    user.getId());
// 返回错误信息
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 更新点赞数
        articleService.thumbsUpById(id);
// 返回结果
        return AppResult.success();
    }

    @Operation(summary = "删除帖⼦")
    @GetMapping("/delete")
    public AppResult deleteById (HttpServletRequest request,
                                 @Parameter(description = "帖⼦Id") @RequestParam("id")
                                 @NotNull Long id) {
// 1. ⽤⼾是否禁⾔
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
// 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
// 查询帖⼦信息
        Article article = articleService.selectById(id);
// 2. 帖⼦是否存在或已删除
        if (article == null || article.getState() == 1) {
// 返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICAL_NOT_EXISTS);
        }
// 3. ⽤⼾是否是作者
        if (article.getUserId() != user.getId()) {
// 返回错误描述
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
// 调⽤Service执⾏删除
        articleService.deleteById(id);
// 返回成功
        return AppResult.success();
    }


    /**
     * 根据⽤⼾Id查询帖⼦列表
     * @param userId ⽤⼾Id
     * @return 指定版块的帖⼦列表
     */
    @Operation(summary = "根据⽤⼾Id查询帖⼦列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                            @Parameter(description = "⽤⼾Id")
                            @RequestParam(value = "userId" , required = false)  Long userId) {
        // 查询⽤⼾的帖⼦列表
        if (userId == null) {
            userId = ((User) request.getSession().getAttribute(AppConfig.USER_SESSION)).getId();
        }
        List<Article> result = articleService.selectByUserId(userId);
        log.info("查询⽤⼾帖⼦列表, userId = " + userId);
        // 返回结果
        return AppResult.success(result);
    }
}
